package com.tl.khadmin.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpSession;

import com.tl.khadmin.HaolibeiApi;
import com.tl.khadmin.bean.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.tl.khadmin.bean.dto.CityInfoDto;
import com.tl.khadmin.bean.dto.DistrictListDto;
import com.tl.khadmin.bean.dto.FreightListDto;
import com.tl.khadmin.bean.dto.ProvinceDto;
import com.tl.khadmin.mapper.FreightMapper;
import com.tl.khadmin.mapper.FreightRegionMapper;
import com.tl.khadmin.mapper.FreightTemplateMapper;
import com.tl.khadmin.mapper.LogisticsMapper;
import com.tl.khadmin.mapper.ProductBrandMapper;
import com.tl.khadmin.page.Page;
import com.tl.khadmin.service.FreightIService;
import com.tl.khadmin.service.LogisticsIService;
import com.tl.khadmin.service.ProductBrandIService;
import com.tl.khadmin.util.CommonUtil;
import com.tl.khadmin.util.Constant;
import com.tl.khadmin.util.PutParamUtil;

@Service
public class FreightServiceImpl implements FreightIService {

    @Resource
    private FreightMapper freightMapper;
    @Resource
    private FreightRegionMapper freightRegionMapper;
    @Resource
    private FreightTemplateMapper freightTemplateMapper;
    
	@Override
	public String updateFreightTemplate(FreightTemplate freightTemplate) {
		Integer id = freightTemplateMapper.queryIdByNameAndId(freightTemplate.getId(), freightTemplate.getTemplateName());
        if (id != null) {
            return CommonUtil.returnMapResultToJson("fail", "名称已经存在");
        }
        int result = freightTemplateMapper.updateByPrimaryKeySelective(freightTemplate);
        return CommonUtil.returnMapResultByRows(result, "修改成功", "修改失败，请重试");
	}
	
	@Override
	public FreightTemplate queryFreightTemplate(Integer id) { 
		return freightTemplateMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public List<FreightTemplate> listFreightTemplate(HttpSession session, Map<String, Object> param) { 
		Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
		param.put("supplierId", supplier.getId());
		return freightTemplateMapper.list(param);
	}
    
    /**
     * 新增运费模板 FreightTemplate
     */
	@Override
	public String saveFreightTemplate(HttpSession session, FreightTemplate freightTemplate) {
		if(freightTemplateMapper.queryByName(freightTemplate.getTemplateName()) > 0) {
			return CommonUtil.returnMapResultToJson("fail", "名称已经存在");
		} 
		Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
		Staff staff = (Staff) session.getAttribute(Constant.USER);
		freightTemplate.setSupplierId(supplier.getId());
		freightTemplate.setCreateId(staff.getId());
		freightTemplate.setCreateTime(new Date());
		int result = freightTemplateMapper.insertSelective(freightTemplate);
        return CommonUtil.returnMapResultByRows(result, "提交成功", "保存失败，请重试");
	}

    public List<Freight> listFreight(HttpSession session, Map<String, Object> param) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        PutParamUtil.setParamIsInterior(supplier, param);    //设置查询供应商数据范围
//		param.put("supplierId", supplier.getId());
        return freightMapper.listFreight(param);
    }

    @Override
    public String updateFreight(Freight freight) {
        Integer id = freightMapper.queryIdByNameAndId(freight.getId(), freight.getFreightName());
        if (id != null) {
            return CommonUtil.returnMapResultToJson("fail", "名称已经存在");
        }
        int result = freightMapper.updateByPrimaryKeySelective(freight);
        return CommonUtil.returnMapResultByRows(result, "修改成功", "修改失败，请重试");
    }

    @Override
    public Page<FreightListDto> showFreightByPage(HttpSession session, Integer pageNum,
                                                  Integer pageSize, Map<String, Object> params) {
        Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
        params.put("supplierId", supplier.getId());
        Page<FreightListDto> page = new Page<FreightListDto>(pageNum, pageSize);
        params.put("page", page);
        List<FreightListDto> list = freightMapper.showFreightByPage(params);
        for (FreightListDto dto : list) {
            dto.setFreightRegionList(freightRegionMapper.findFreightRegionByFreightId(dto.getId()));
        }
        page.setResult(list);
        return page;
    }

    @Override
    public String saveFreight(HttpSession session, Freight freight, String regionVals) {
        Integer id = freight.getId();
        //id为空则为新增操作
        try {
            if (id == null) {
                Staff staff = (Staff) session.getAttribute(Constant.USER);
                Supplier supplier = (Supplier) session.getAttribute(Constant.USER_SUPPLIER);
                Integer idIsExit = freightMapper.queryIdByName(freight.getFreightName(), supplier.getId());
                if (idIsExit != null) {
                    return CommonUtil.returnMapResultToJson("fail", "名称已经存在");
                }
                freight.setCreateId(staff.getId().longValue());
                freight.setSupplierId(supplier.getId());
                freight.setCreateTime(new Date());
                int result = freightMapper.insertSelective(freight);
                if (result != 1) {
                    return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
                }
            } else {
                //修改操作
                int result = freightMapper.updateByPrimaryKeySelective(freight);
                if (result != 1) {
                    return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
                }
                freightRegionMapper.deleteByRegionId(freight.getId());
            }

            //插入运费模板区域，区域
            String[] regions = regionVals.split(",");
            List<String> topCity = new ArrayList<>();
            List<String> lastCity = new ArrayList<>();
            List<DistrictListDto> districtListDtoList = new ArrayList<>();
            for (String districtId : regions) {
                if (StringUtils.isNotBlank(districtId)) {
                    FreightRegion freightRegion = new FreightRegion();
                    Integer did = Integer.parseInt(districtId);
                    DistrictListDto districtDto = freightRegionMapper.findDistrictById(did);
                    freightRegion.setProvinceId(districtDto.getPpid());
                    freightRegion.setCityId(districtDto.getPid());
                    freightRegion.setDistrictId(did);
                    freightRegion.setPdcName(districtDto.getMergername());
                    freightRegion.setFreightId(freight.getId());
                    String[] freightRegionArray = freightRegion.getPdcName().split(",");
                    if (!topCity.contains(freightRegionArray[0])) {
                        topCity.add(freightRegionArray[0]);
                    }
                    lastCity.add(freightRegionArray[freightRegionArray.length - 1]);
                    districtListDtoList.add(districtDto);
                    freightRegionMapper.insertSelective(freightRegion);
                }
            }
            YiFanRegionSync(topCity, lastCity, freight, districtListDtoList);
        } catch (NumberFormatException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            return CommonUtil.returnMapResultByRows(0, "提交成功", "提交失败，请重试");
        }
        return CommonUtil.returnMapResultByRows(1, "提交成功", "提交失败，请重试");
    }

    private void YiFanRegionSync(List<String> topCity, List<String> lastCity, Freight freight, List<DistrictListDto> districtListDtoList) {
        try {
            Map<Integer, List<DistrictListDto>> groupLevel = districtListDtoList.stream().collect(Collectors.groupingBy(t -> t.getLeveltype()));
            List<DistrictListDto> chooseList = new ArrayList<>();

            List<DistrictListDto> level3 = groupLevel.get(3);
            if (level3 != null && level3.size() > 0) {
                Map<Integer, List<DistrictListDto>> groupPid = level3.stream().collect(Collectors.groupingBy(t -> t.getPid()));
                for (Map.Entry<Integer, List<DistrictListDto>> item : groupPid.entrySet()
                ) {
                    DistrictListDto districtDto = freightRegionMapper.findDistrictById(item.getKey());
                    Integer childCount = freightRegionMapper.countDistrictByPid(districtDto.getId());
                    if (item.getValue().size() == childCount) {
                    	if(groupLevel.keySet().contains(2)) {
							DistrictListDto parent = groupLevel.get(2).stream().filter(p -> p.getId().compareTo(item.getKey()) == 0).findFirst().orElse(null);
							if (parent != null) {
								parent.setChooseAll(true);
							} else {
								districtDto.setChooseAll(true);
								groupLevel.get(2).add(districtDto);
							}
						}
                    	else {
                    	    districtDto.setChooseAll(true);
                    		groupLevel.put(2,new ArrayList<DistrictListDto>(){{add(districtDto);}});
						}
                    } else {
                        chooseList.addAll(item.getValue());
                    }
                }
            }
            if(groupLevel.keySet().contains(2)) {
                List<DistrictListDto> level2 = groupLevel.get(2);
                if (level2 != null && level2.size() > 0) {
                    Map<Integer, List<DistrictListDto>> groupPid = level2.stream().collect(Collectors.groupingBy(t -> t.getPid()));
                    for (Map.Entry<Integer, List<DistrictListDto>> item : groupPid.entrySet()
                    ) {
                        DistrictListDto districtDto = freightRegionMapper.findDistrictById(item.getKey());
                        int childCount = freightRegionMapper.countDistrictByPid(districtDto.getId());
                        List<DistrictListDto> chooseAllLevel2 = item.getValue().stream().filter(p -> p.getChooseAll()).collect(Collectors.toList());
                        if (chooseAllLevel2 != null) {
                            if (chooseAllLevel2.size() == childCount) {
                                districtDto.setChooseAll(true);
                                chooseList.add(districtDto);
                            } else if (item.getValue().size()>0) {
                                chooseList.add(districtDto);
                                chooseList.addAll(item.getValue());
                            }
                        }

                    }
                }
            }

            Freight reloadFreight = freightMapper.selectByPrimaryKey(freight.getId());
            freight.setSupplierId(reloadFreight.getSupplierId());

            FreightTemplate freightTemplate = freightTemplateMapper.selectByPrimaryKey(freight.getFreightTemplateId());

            YiFanFrigthRegion region = new YiFanFrigthRegion();
            region.setFreightTemplateName(String.format("%s_gyl_%s", freightTemplate.getTemplateName(), freight.getSupplierId()));
            region.setRegionId(freight.getId());
            region.setFirstHeavyFreight(freightTemplate.getFirstHeavyFreight());
            region.setFirstHeavy(freightTemplate.getFirstHeavy());
            region.setOtherHeavyFreight(freightTemplate.getOtherHeavyFreight());
            region.setOtherHeavy(freightTemplate.getOtherHeavy());
            region.setFreight(freight);
            region.getFreight().setFreightName(String.format("%s_gyl_%s", freightTemplate.getTemplateName(), freight.getSupplierId()));
			region.setChooseList(chooseList);
            HaolibeiApi.FreightRegionSync(region,false);
        } catch (Exception ex) {

        }
    }

    @Override
    public String deleteByIds(String ids) {
        String[] idsArr = ids.substring(0, ids.length() - 1).split(",");
        try {
            if (freightMapper.deleteByIds(idsArr) > 0) {

                return CommonUtil.returnMapResultByRows(1, "删除成功", "删除失败，请重试");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return CommonUtil.returnMapResultByRows(0, "删除成功", "该数据不能删除");
        }
        return CommonUtil.returnMapResultByRows(0, "删除成功", "删除失败，请重试");
    }

    private void deleteYiFanRegion(String[] idsArr){
	    try {
            for (String item : idsArr
            ) {
                YiFanFrigthRegion region = new YiFanFrigthRegion();
                region.setRegionId(Integer.valueOf(item).intValue());
                HaolibeiApi.FreightRegionSync(region,true);
            }
        }
	    catch (Exception ex){

        }
    }
    @Override
    public Map<String, Object> queryFreightById(String freightId) {
        Map<String, Object> result = new HashMap<>();
        Freight freight = null;
        String selectedCityIds = null;
        //修改操作
        if (StringUtils.isNotBlank(freightId)) {
            freight = freightMapper.selectByPrimaryKey(Integer.parseInt(freightId));
            List<Integer> selectedList = freightRegionMapper.findDistrictByFreightId(Integer.parseInt(freightId));
            selectedCityIds = StringUtils.join(selectedList.toArray(), ",");
        }
        //加载所有地区
        List<ProvinceDto> provinceList = this.parseFreightRegion();
        result.put("selectedDistrictIds", "," + selectedCityIds + ",");
        result.put("provinceList", provinceList);
        result.put("freight", freight);
        return result;
    }

    /**
     * 获取运费模板地区数据
     *
     * @param freightId
     */
    private List<ProvinceDto> parseFreightRegion() {
        List<ProvinceDto> provinceList = freightRegionMapper.listProvinceDto();
        return provinceList;
    }

    @Override
    public String updateStatus(Freight freight) {
        int result = freightMapper.updateByPrimaryKeySelective(freight);
        return CommonUtil.returnMapResultByRows(result, "修改成功", "修改失败，请重试");
    }

}
